<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 股权投资信息 -->
          <div class="project-part">
            <div class="project-part-title">企业信息</div>

            <el-row>
              <el-col :span="6">
                <el-form-item label="企业名称" prop="name">
                  <el-select
                    v-model.trim="basicForm.name"
                    :disabled="isDetail"
                    placeholder="请选择"
                    filterable
                    allow-create
                    default-first-option
                    @change="handleSelectChange"
                  >
                    <el-option
                      v-for="item in enterpriseOptions"
                      :key="item.socialCode"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="统一社会信用代码"
                  prop="socialCode"
                >
                  <el-input
                    v-model="basicForm.socialCode"
                    placeholder="请输入"
                    :disabled="isDetail || isExisting"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="当前估值(亿元)">
                  <el-input
                    v-model="basicForm.investment"
                    placeholder="请输入"
                    :disabled="isDetail"
                    type="number"
                  ></el-input>
                </el-form-item>
              </el-col>

              <!-- <el-col :span="6">
                <el-form-item label="投资金额(万元)">
                  <el-input
                    v-model="basicForm.investment"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col> -->

              <!-- <el-col :span="6">
                <el-form-item label="投资时间">
                  <el-date-picker
                    v-model="basicForm.investTime"
                    type="date"
                    placeholder="选择日期"
                    :disabled="isDetail"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col> -->
            </el-row>
          </div>
          <!-- 融资构成 -->
          <div class="project-part">
            <div class="project-part-title">融资构成</div>
            <el-button
              icon="el-icon-plus"
              class="add-button"
              v-if="!isDetail"
              @click="addInvestment"
              >新增</el-button
            >
          </div>
          <el-table
            :data="basicForm.capitalContributionInfo"
            class="year-table"
            :header-cell-style="{
              background: '#F2F6FB',
              color: ' #6B767D'
            }"
          >
            <el-table-column
              label="投资主体"
              prop="capitalContributionName"
            >
              <template slot-scope="scope">
                <span v-if="isDetail">
                  {{ scope.row.capitalContributionName }}
                </span>
                <el-input
                  v-else
                  v-model="
                    scope.row.capitalContributionName
                  "
                  placeholder="请输入"
                  class="num-input"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column
              label="投资金额(万元)"
              prop="capitalContributionPrice"
            >
              <template slot-scope="scope">
                <span v-if="isDetail">
                  {{ scope.row.capitalContributionPrice }}
                </span>
                <el-input
                  v-else
                  v-model="
                    scope.row.capitalContributionPrice
                  "
                  :disabled="isDetail"
                  placeholder="请输入"
                  class="num-input"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column
              label="投资阶段"
              prop="capitalContributionStage"
            >
              <template slot-scope="scope">
                <span v-if="isDetail">
                  {{ scope.row.capitalContributionStage }}
                </span>
                <el-input
                  v-else
                  v-model="
                    scope.row.capitalContributionStage
                  "
                  :disabled="isDetail"
                  placeholder="请输入"
                  class="num-input"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column
              label="投资时间"
              prop="capitalContributionTime"
            >
              <template slot-scope="scope">
                <span v-if="isDetail">
                  {{ scope.row.capitalContributionTime }}
                </span>
                <el-date-picker
                  v-else
                  v-model="
                    scope.row.capitalContributionTime
                  "
                  :disabled="isDetail"
                  type="date"
                  class="num-input"
                  placeholder="请选择"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column
              label="投资时股权占比(%)"
              prop="equityPercentage"
            >
              <template slot-scope="scope">
                <span v-if="isDetail">
                  {{ scope.row.equityPercentage }}
                </span>
                <el-input
                  v-else
                  v-model="scope.row.equityPercentage"
                  :disabled="isDetail"
                  placeholder="请输入"
                  class="num-input"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column
              v-if="!isDetail"
              label="操作"
              width="180"
            >
              <template slot-scope="scope">
                <el-button
                  @click="deleteInvestment(scope.$index)"
                  type="text"
                  :disabled="isDetail"
                  style="color: #ff5b5b; font-weight: 400"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import {
  addEquityInfo,
  enterpriseInfoQuery,
  addEnterpriseInfo
} from '@/api/dataManagement'
import dayjs from 'dayjs'

export default {
  props: {
    pkid: String,
    title: String,
    data: Object,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Breadcrumb
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        name: '',
        socialCode: '',
        investment: '',
        capitalContributionInfo: []
      },
      basicRules: {
        name: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: 'blur'
          }
        ],
        socialCode: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      enterpriseOptions: [],
      addEnterpriseInfo: {
        name: '',
        socialCode: '',
        type: '',
        enterpriseId: ''
      },
      isExisting: false
    }
  },
  computed: {
    titles() {
      return [this.title]
    }
  },
  mounted() {
    this.isEdit
      ? (this.isExisting = true)
      : (this.isExisting = false)
    this.getEnterpriseOptions()
    if (this.pkid && this.data) {
      this.basicForm = JSON.parse(JSON.stringify(this.data))
    }
  },
  methods: {
    handleSelectChange(val) {
      const value = String(val).trim()
      this.isExisting = this.enterpriseOptions.some(
        (item) => item.name === value
      )

      if (!this.isExisting) {
        this.addEnterpriseInfo.name = value
        this.basicForm.socialCode = ''
      } else {
        // 选择现有企业
        // this.manualInputName = ''
        const enterpriseInfo = this.enterpriseOptions.find(
          (item) => item.name === value
        )
        this.basicForm.socialCode =
          enterpriseInfo.socialCode
        this.basicForm.name = enterpriseInfo.name
        this.addEnterpriseInfo.enterpriseId =
          enterpriseInfo.pkid
      }
    },
    // handleSelectBlur() {
    //   // 如果是手动输入的企业名称且当前值为空，恢复手动输入的值
    //   if (!this.isExisting && this.manualInputName && !this.basicForm.name) {
    //     this.$nextTick(() => {
    //       this.basicForm.name = this.manualInputName
    //     })
    //   }
    // },
    getEnterpriseOptions() {
      enterpriseInfoQuery({
        pageIndex: 1,
        pageSize: 999
      }).then((res) => {
        if (res.success) {
          this.enterpriseOptions = res.data.list
        }
      })
    },
    async saveInfo() {
      this.$refs.basicFormRef.validate(async (res) => {
        if (res) {
          try {
            // 如果是新企业，先添加企业信息
            if (!this.isExisting) {
              this.addEnterpriseInfo.enterpriseId = ''
              this.addEnterpriseInfo.socialCode =
                this.basicForm.socialCode
              this.addEnterpriseInfo.type = '' // 股权投资企业可以设置默认类型或留空
              this.addEnterpriseInfo.name =
                this.basicForm.name

              // const enterpriseRes = await addEnterpriseInfo(this.addEnterpriseInfo)
              // if (!enterpriseRes.success) {
              //   this.$message.error(enterpriseRes.message || '企业信息保存失败')
              //   return
              // }
            }

            this.basicForm.enterpriseId =
              this.addEnterpriseInfo.enterpriseId
            let formData = { ...this.basicForm }

            // Format invest time
            formData.capitalContributionInfo.forEach(
              (item) => {
                if (item.capitalContributionTime) {
                  item.capitalContributionTime = dayjs(
                    item.capitalContributionTime
                  ).format('YYYY-MM-DD')
                }
              }
            )

            this.loading = true
            const equityRes = await addEquityInfo(formData)
            this.loading = false
            if (equityRes.success) {
              this.$message.success(
                this.pkid ? '编辑成功' : '保存成功'
              )
              this.$router.push({
                path: '/dataManagement/equityInvestment/list',
                query: { refresh: Date.now() }
              })
            } else {
              this.$message.error(equityRes.message)
            }
          } catch (error) {
            this.loading = false
            this.$message.error('保存失败，请重试')
          }
        }
      })
    },
    addInvestment() {
      this.basicForm.capitalContributionInfo.push({
        capitalContributionName: '',
        capitalContributionPrice: '',
        capitalContributionStage: '',
        capitalContributionTime: '',
        equityPercentage: ''
      })
    },
    deleteInvestment(index) {
      this.basicForm.capitalContributionInfo.splice(
        index,
        1
      )
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    padding: 10px 0 0 20px;

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .line {
    display: flex;
    justify-content: center;
  }
  .project-part {
    position: relative;
  }
  .add-button {
    position: absolute;
    left: 0;
    top: 0;
    width: 100px;
    height: 32px;
    background: #497fa3;
    border-radius: 4px;
    color: #fff;
    font-size: 14px;
    font-weight: 400;
    margin-left: 150px;
    margin-top: -5px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

::v-deep .num-input .el-input__inner {
  max-width: 200px;
}

:deep(.el-input__icon) {
  line-height: 30px;
}
</style>
